package com.deri.egov.vor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.deri.vor.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class GMapsActivity extends MapActivity {

	private MapView mapView;
	private String keyword;
	private String longitude;
	private String latitude;
	private String radius;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Intent intent = getIntent();
		ArrayList<String> stringArrayListExtra = intent
				.getStringArrayListExtra("data");
		keyword = stringArrayListExtra.get(3);
		longitude = stringArrayListExtra.get(1);
		latitude = stringArrayListExtra.get(0);
		radius = stringArrayListExtra.get(2);
		ArrayList<PointOfInterest> pois = postData(radius, latitude, longitude,
				keyword);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tag_map);

		mapView = (MapView) findViewById(R.id.GalwayMapview);
		mapView.setBuiltInZoomControls(true);
		
		share_button();
		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(
				R.drawable.pin);
		CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
				drawable, this);

		GeoPoint point = getPoint(Double.valueOf(longitude),
				Double.valueOf(latitude));
		OverlayItem overlay = new OverlayItem(point, "", "  You Are Here  ");
		itemizedOverlay.addOverlay(overlay);
		mapOverlays.add(itemizedOverlay);
		MapController mapController = mapView.getController();
		this.createMarkers(mapOverlays, pois);
		mapController.setCenter(point);
		if(Integer.valueOf(radius)>8000){
		  mapController.setZoom(12);
		}
		else
		{
			mapController.setZoom(14);
		}
	}

	private static GeoPoint getPoint(double lon, double lat) {
		return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
	}

	private void createMarkers(List<Overlay> mapOverlays,
			ArrayList<PointOfInterest> arrayList) {

		for (int i = 0; i < arrayList.size(); i++) {
			PointOfInterest pointOfInterest = arrayList.get(i);

			Drawable drawable = getDrawable(pointOfInterest.getType());
			CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
					drawable, this);
			OverlayItem overlay = new OverlayItem(getPoint(
					pointOfInterest.getLon(), pointOfInterest.getLat()),
					keyword, getAlertMsg(pointOfInterest));
			itemizedOverlay.addOverlay(overlay);
			mapOverlays.add(itemizedOverlay);
		}

	}

	private String getAlertMsg(PointOfInterest pointOfInterest) {
		String msg = " "+pointOfInterest.getName() 
		+ "\n Longitude :"+ pointOfInterest.getLon() 
		+ "\n Latitude :"+ pointOfInterest.getLat();
		if (!pointOfInterest.getUrl().equals("null")) {
			msg += "\n More : "+pointOfInterest.getUrl();
		}
		return msg;
	}

	private Drawable getDrawable(String type) {
		Drawable type_icon;
		if (type.contains("latinquarter")) {
			type_icon = this.getResources().getDrawable(
					R.drawable.lationquarter);
		} else if (type.contains("museum")) {
			type_icon = this.getResources().getDrawable(R.drawable.museum);
		} else if (type.contains("atm")) {
			type_icon = this.getResources().getDrawable(R.drawable.atm);
		}else if (type.contains("beach")) {
			type_icon = this.getResources().getDrawable(R.drawable.bucket_icon);
		} else if (type.equals("park")) {
			type_icon = this.getResources().getDrawable(R.drawable.park);
		}else if (type.contains("carpark")) {
			type_icon = this.getResources().getDrawable(R.drawable.carpark);
		}else {
			type_icon = this.getResources().getDrawable(R.drawable.pin);
		}
		return type_icon;

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	// GOFRAN : changed the return type to return arraylist of POI
	private ArrayList<PointOfInterest> postData(String Radius, String Latitude,
			String Longitude, String Keyword) {

		ArrayList<PointOfInterest> arrayList = new ArrayList<PointOfInterest>();// GOFRAN:
																				// array
																				// definition
		String url = "http://vmusm01.deri.ie/vor/poi_request_listen_test-egov-virtuoso.php?";
		String final_url = url + "Radius=" + Radius + "&Latitude=" + Latitude
				+ "&Longitude=" + Longitude + "&Keyword="
				+ Keyword.toLowerCase();
		URL Url = null;

		try {
			Url = new URL(final_url);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(Url.openStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String inputLine = "", finalLine = "";
		try {
			while ((inputLine = in.readLine()) != null)
				finalLine = finalLine + inputLine;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (finalLine.equals("empty")) {
				Toast.makeText(
						getBaseContext(),
						"No locations tagged with " + Keyword + " within "
								+ radius + " meters", Toast.LENGTH_LONG).show();
			} else {
				JSONObject jsonObj = new JSONObject(finalLine);
				JSONObject pois = jsonObj.getJSONObject("pois");

				// using JSONArray to grab the menuitems from under popop
				JSONArray poiArr = pois.getJSONArray("poilist");

				// lets loop through the JSONArray and get all the items
				for (int i = 0; i < poiArr.length(); i++) {
					// printing the values to the logcat
					String name = poiArr.getJSONObject(i).getString("name")
							.toString();
					String latitude = poiArr.getJSONObject(i)
							.getString("latitude").toString();
					String longitude = poiArr.getJSONObject(i)
							.getString("longitude").toString();
					String type = poiArr.getJSONObject(i).getString("type")
							.toString();
					String link = (poiArr.getJSONObject(i).getString("url") != null ? poiArr
							.getJSONObject(i).getString("url").toString()
							: null);
					PointOfInterest pointOfInterest = new PointOfInterest(name,
							new Double(longitude).doubleValue(), new Double(
									latitude).doubleValue(), type, link);
					arrayList.add(pointOfInterest);
				}
			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return arrayList;
	}
	
	 private OnClickListener ms_layout	=	new OnClickListener(){

			@Override
			public void onClick(View v) {
				switch (v.getId()){
				case R.id.btnAbout  : { jump(72); break;}
				case R.id.btnHome 	: { jump(2); break;}
				case R.id.btnBack  	: { goback(); break;}

				}
			}
	    };

	    private void goback(){
	    	Intent i = new Intent();
	    	i.setClassName("org.deri.vor", "com.deri.egov.vor.POISearchActivity");
	    	finish();
			startActivity(i);
	    }
	    
	    private void jump(int page){
	    	Intent i = new Intent();
	    	i.putExtra("cl",page);
	    	i.setClassName("org.deri.vor", "org.deri.vor.VovolOceanRaceActivity");
	    	finish();
			startActivity(i);
		
	    }
	    
		private void share_button(){
			Button button = (Button) findViewById(R.id.btnBack);
			button.setOnClickListener(ms_layout);

			// About Button OnClick
			button = (Button) findViewById(R.id.btnAbout);
			button.setOnClickListener(ms_layout);

			// Home Button OnClick
			button = (Button) findViewById(R.id.btnHome);
			button.setOnClickListener(ms_layout);
			
//		
		}
	    
	
	
}